<?php

namespace App\Http\Controllers\Api;

use App\Jobs\SendTemplateMessage;
use App\Models\Wxuser;
use App\Models\WxuserStar;
use App\Repositories\IndexRepository;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class StarController extends Controller
{
    use Helpers;

    const ERR_CODE = array(
        'SUCCESS' => '100',
        'WXUSER_NOTFOUND' => '1001',
    );

    //$wxuser = $indexRepository->CreateOrUpdateWxuser(['unionid'=>$unionid]);
    public function add(Request $request,IndexRepository $indexRepository)
    {
        $unionid = $request->post('unionid', null);
        $star = $request->post('star', 1);
        $id_tradedetail = $request->post('id_tradedetail', 1);

        $wxuser = $indexRepository->CreateOrUpdateWxuser(['unionid'=>$unionid]);

        /*if(empty($wxuser)){
            return $this->response->array(array(
                'message' => 'unionid invalid.',
                'code' => self::ERR_CODE['WXUSER_NOTFOUND']
            ));
        }*/

        $bef = $wxuser->total_stars*1;
        $aft = $wxuser->total_stars*1+$star*1;

        $wxuser_start = WxuserStar::create([
            'id_wxusers'=>$wxuser->id,
            'num'=>$star*1,
            'wxuser_num_before'=>$bef,
            'wxuser_num_after'=>$aft,
            'id_tradedetail'=>$id_tradedetail,
        ]);

        //推送模板消息
        if(!empty($wxuser->openid)){
            $data =  [
                "touser"=>$wxuser->openid,
                "template_id"=>'xbc8yalt3MQW5lD3GeeAKAcjwhg6_5NiD1hNNUOiCDU',
                "url"=>'http://'.$_SERVER['SERVER_NAME'],

                "data"=>[
                    "first"=> [
                        "value"=>"慈善心相悦，公益心相印"."\r\n",
                        "color"=>"#173177"
                    ],
                    "keyword1"=>[
                        "value"=>'爱在同行',
                        "color"=>"#173177"
                    ],
                    "keyword2"=> [
                        "value"=>date('Y-m-d'),
                        "color"=>"#173177"
                    ],
                    "keyword3"=> [
                        "value"=>'0.1元',
                        "color"=>"#173177"
                    ],
                    "remark"=>[
                        "value"=>'爱心接力，牵起爱心的手',
                        "color"=>"#173177"
                    ]
                ]
            ];
            app('EasyWechatOfficial')->template_message->send($data);
            //或推送到队列处理
            //dispatch(new SendTemplateMessage($wxuser_start));
        }


        return $this->response->array(array(
            'message' => 'success',
            'code' => self::ERR_CODE['SUCCESS']
        ));


    }
}
